/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 10:50:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-23 14:34:50
 * @Description: 入口启动文件
 */

import Koa from "koa";
const app = new Koa();
/*引入本地配置文件*/
global.globalConfig = {};
try {
  const configPath =
    process.env.NODE_ENV == "production"
      ? "./config.prd.js"
      : "./config.env.js";
  console.log(configPath, "configPath");
  global.globalConfig = (await import(configPath)).default;
} catch {
  console.info("加载本地配置文件失败~");
}
/*引入工具*/
await import("./tool/index.js");
/*静态文件解析*/
import fs from "fs";
import path from "path";
import koaStatic from "koa-static";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
global.publicPath = path.join(__dirname, "../public");
app.use(koaStatic(global.publicPath));
app.use(async (ctx, next) => {
  if (ctx.path == "/") ctx.path = "/h5";
  if (ctx.path.startsWith("/h5") || ctx.path.startsWith("/manageSystem")) {
    console.log("访问静态页面");
    ctx.response.type = "html";
    console.log(ctx.path.split("/")[1]);
    ctx.response.body = fs.createReadStream(
      path.join(publicPath, `/${ctx.path.split("/")[1]}/index.html`)
    );
  } else {
    await next();
  }
});
/*校验token*/
const Login = await import("./router/login.js");
const checkToken = Login.default.checkToken.bind(Login.default);
app.use(checkToken);
/*请求参数及上传文件处理*/
import koaBody from "koa-body";
app.use(async (ctx, next) => {
  await koaBody.default({
    multipart: true,
    formidable: {
      // 保持后缀名
      keepExtensions: true,
      // 文件大小
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认200M
    },
    patchKoa: !ctx.url.split("/")[1].includes("uploadToJava"), //直接上传文件到后台的情况
  })(ctx, next);
});

/*设置路由*/
const useRouter = await import("./router/index.js");
app.use(useRouter.default.routes());

/*代理请求*/
import koaBetterHttpProxy from "koa-better-http-proxy";
app.use(async (ctx, next) => {
  try {
    await koaBetterHttpProxy("https://www.wjx.cn", {
      changeOrigin: true,
      // 响应拦截
      // userResDecorator: resHandle.default,
    })(ctx, next);
  } catch (err) {
    ctx.body = {
      result: "fail",
      message: "出错了，请查看日志",
    };
    log.error(err);
  }
});

/*报错打印*/
app.on("error", (err, ctx) => {
  log.error("server error", err, ctx);
});

/*启动服务*/
const port = globalConfig.port || 8080;
const server = app.listen(port);
//设置超时
const timeOut = globalConfig.timeOut || 0;
server.setTimeout(timeOut);

// 启动成功
log.info(`服务运行成功，端口号：${port}`);
